package com.ktvme.process;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ktvme.core.AbstractOperator;
import com.ktvme.core.DolphinException;
import com.ktvme.core.DolphinClientConstant;
import com.ktvme.result.PageResult;
import com.ktvme.utils.HttpUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class ProcessOperator extends AbstractOperator {

    public ProcessOperator(String baseUrl, String token) {
        super(baseUrl, token);
    }

    /**
     * 分页查询流程定义列表
     *
     * @param projectCode 项目 Code
     * @param pageNo      页码号
     * @param pageSize    页大小
     * @param searchVal   搜索值（可选）
     * @return 分页查询结果
     */
    public PageResult<ProcessDefineResp> page(
            long projectCode, int pageNo, int pageSize, String searchVal) {

        String url = baseUrl + "/projects/" + projectCode + "/process-definition";

        // 构建请求参数
        Map<String, String> params = new HashMap<>();
        params.put("pageNo", String.valueOf(pageNo));
        params.put("pageSize", String.valueOf(pageSize));

        // 只有当参数不为空时才添加到请求参数中
        if (searchVal != null && !searchVal.isEmpty()) {
            params.put("searchVal", searchVal);
        }

        try {
            String jsonString = HttpUtil.sendGetRequest(url, params, token);
            JSONObject jsonObject = JSON.parseObject(jsonString);

            if (jsonObject == null) {
                throw new DolphinException("响应数据为空");
            }

            JSONObject data = jsonObject.getJSONObject("data");
            JSONArray totalList = data.getJSONArray("totalList");

            if (data == null || data.isEmpty()) {
                throw new DolphinException("数据列表为空");
            }

            List<ProcessDefineResp> javaList = totalList.toJavaList(ProcessDefineResp.class);
            PageResult<ProcessDefineResp> pageResult = new PageResult<>();
            pageResult.setRecords(javaList);
            pageResult.setCurrentPage(pageNo);
            pageResult.setPageSize(pageSize);

            Integer totalPages = data.getInteger("totalPage");
            Integer totalRecord = data.getInteger("total");

            pageResult.setTotalPages(totalPages);
            pageResult.setTotalRecord(totalRecord);

            return pageResult;
        } catch (IOException e) {
            throw new DolphinException("获取流程定义列表失败", e);
        }
    }

    /**
     * 创建流程定义（工作流）
     *
     * @param projectCode 项目 Code
     * @param processDefineParam 创建流程参数
     * @return 创建响应结果
     */
//    public ProcessDefineResp createProcessDefinition(Long projectCode, ProcessDefinitionResp processDefineParam) {
//        String url = baseUrl + "/projects/" + projectCode + "/process-definition";
//        log.info("创建流程定义, URL: {}, 参数: {}", url, processDefineParam);
//        try {
//            String responseJson = HttpUtil.sendPostRequest(url, processDefineParam, token);
//            JSONObject jsonResponse = JSON.parseObject(responseJson);
//            if (jsonResponse.getBoolean("success")) {
//                return JSON.parseObject(jsonResponse.getString("data"), ProcessDefineResp.class);
//            } else {
//                log.error("海豚调度器响应: {}", jsonResponse);
//                throw new DolphinException("创建流程定义失败");
//            }
//        } catch (IOException e) {
//            throw new DolphinException("创建流程定义失败", e);
//        }
//    }

    /**
     * 更新流程定义（工作流）
     *
     * @param projectCode 项目 Code
     * @param processDefineParam 更新流程参数
     * @param processCode 流程 Code
     * @return 更新响应结果
     */
//    public ProcessDefinitionResp updateProcessDefinition(Long projectCode, ProcessDefinitionResp processDefineParam, Long processCode) {
//        String baseUrl = this.url + "/projects/" + projectCode + "/process-definition/" + processCode;
//        log.info("更新流程定义, URL: {}, 参数: {}", url, processDefineParam);
//        try {
//            String responseJson = HttpUtil.sendPutRequest(baseUrl, processDefineParam, token);
//            JSONObject jsonResponse = JSON.parseObject(responseJson);
//            if (jsonResponse.getBoolean("success")) {
//                return JSON.parseObject(jsonResponse.getString("data"), ProcessDefineResp.class);
//            } else {
//                log.error("海豚调度器响应: {}", jsonResponse);
//                throw new DolphinException("更新流程定义失败");
//            }
//        } catch (IOException e) {
//            throw new DolphinException("更新流程定义失败", e);
//        }
//    }

    /**
     * 删除流程定义（工作流）
     *
     * @param projectCode 项目 Code
     * @param processCode 流程 Code
     * @return 删除是否成功
     */
    public Boolean deleteProcessDefinition(Long projectCode, Long processCode) {
        String url = baseUrl + "/projects/" + projectCode + "/process-definition/" + processCode;
        log.info("删除流程定义, 流程Code: {}, URL: {}", processCode, baseUrl);
        try {
            String responseJson = HttpUtil.sendDeleteRequest(url, token);
            JSONObject jsonResponse = JSON.parseObject(responseJson);
            log.info("海豚调度器响应: {}", jsonResponse);
            return jsonResponse.getBoolean("success");
        } catch (IOException e) {
            throw new DolphinException("删除流程定义失败", e);
        }
    }

    /**
     * 发布流程定义（上线/下线）
     *
     * @param projectCode 项目 Code
     * @param processCode 流程 ID
     * @param processReleaseParam 发布参数
     * @return 发布是否成功
     */
    public Boolean publishProcessDefinition(Long projectCode, Long processCode, String processReleaseParam) {
        String url = baseUrl + "/projects/" + projectCode + "/process-definition/" + processCode + "/release";
        log.info("发布流程定义, URL: {}, 参数: {}", url, processReleaseParam);
        try {
            HashMap<String, String> param = new HashMap<>();
            param.put("releaseState", processReleaseParam);
            String responseJson = HttpUtil.sendPostRequestWithParams(url, param, token);
            JSONObject jsonResponse = JSON.parseObject(responseJson);
            return jsonResponse.getBoolean("success");
        } catch (IOException e) {
            throw new DolphinException("发布流程定义失败", e);
        }
    }

    /**
     * 上线流程定义（等同于发布为在线状态）
     *
     * @param projectCode 项目 Code
     * @param code 流程 ID
     * @return 上线是否成功
     */
    public Boolean onlineProcessDefinition(Long projectCode, Long code) {
        return publishProcessDefinition(projectCode, code, DolphinClientConstant.ONLINE_RELEASE_STATE);
    }

    /**
     * 下线流程定义（等同于发布为离线状态）
     *
     * @param projectCode 项目 Code
     * @param code 流程 ID
     * @return 下线是否成功
     */
    public Boolean offlineProcessDefinition(Long projectCode, Long code) {
        return publishProcessDefinition(projectCode, code, DolphinClientConstant.OFFLINE_RELEASE_STATE);
    }

}